package org.jtzc.springaiagent.agent.state;

import org.jtzc.springaiagent.agent.BaseAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wu chuang
 * @description
 */
@Service
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class StatefulAgent implements BaseAgent {
    private final BaseAgent delegate;
    private AgentState state;

    @Autowired
    public StatefulAgent(
            @Qualifier("delegateAgent") BaseAgent delegate) {

        this.delegate = delegate;
        this.state = new AgentState();
    }

    @Override
    public AgentResponse execute(AgentRequest request) {
        // 更新状态
        updateState(request);

        // 丰富请求
        AgentRequest enrichedRequest = enrichRequest(request);

        // 执行
        AgentResponse response = delegate.execute(enrichedRequest);

        // 更新状态
        updateState(response);

        return response;
    }

    private void updateState(AgentRequest request) {
        state.setLastUserInput(request.prompt());
        state.incrementInteractionCount();

        // 分析情绪
        if (request.prompt().contains("!")) {
            state.setUserMood("excited");
        }
    }

    private void updateState(AgentResponse response) {
        state.setLastResponse(response.content());
    }

    private AgentRequest enrichRequest(AgentRequest original) {
        Map<String, Object> enrichedContext = new HashMap<>(original.context());
        enrichedContext.put("state", Map.of(
                "interactionCount", state.getInteractionCount(),
                "userMood", state.getUserMood(),
                "lastTopics", state.getLastTopics()
        ));

        return new AgentRequest(original.prompt(), enrichedContext);
    }
}

